import React, { useState, Suspense, useEffect } from "react";
/*  
  根据location的hash的router容器 
*/
function HashRouter(props) {
  const [origin, setOrigin] = useState(props.basename); // 固定的声明本容器固定location前缀
  const [path, setPath] = useState(location.href); // 记录当前的location值
  // console.log('HashRouter', props, path);
  window.onhashchange = event => {
    console.log('hashChange', event);
    if (event.oldURL === event.newURL) {
      return;
    } else {
      setPath(event.newURL);
    }
  }
  if (!props.config) {
    console.warn('没有导入config文件');
  }
  const list = props.config.map((el) =>
    <HashRouterItem el={el} key={el.path} origin={origin} path={path} />
  );
  return (
    <Suspense fallback={< Loading />}>
      {list}
    </Suspense>
  )
}

function HashRouterItem(props) {
  // console.log(props.el)
  const restLocationStr = props.path.replace(props.origin, '');
  // console.log(restLocationStr, restLocationStr.match((/\/([^\/])*/g)));
  const pageName = restLocationStr.match((/\/([^\/])*/g))[0]; 
  if (pageName && pageName === props.el.path) {
    let params = restLocationStr.match((/\/([^\/])*/g));
    params = params.slice(1, params.length);
    let list = [];
    for(let i of params){
      list.push(i.replace('/',''));      
    }
    params = null;
    return (
      <>
        <props.el.component params={list} />
      </>
    )
  } else {
    return (
      <></>
    )
  }
}

const loadingGif = require('../layout/assets/loading.gif');

function Loading(){
  return(
    <div className="loading-page">
      <img className="loading-page-gif" alt="读取中" src={loadingGif} />
    </div>
  )
}

/* 使用history的路由组件,没有设计多级路由 */
function HistoryRouter(props) {
  const [pageState, setPageState] = useState(history.state);
  const listnerHistory = function(e){
    // console.log(e);
    if(e.detail && e.detail.path != ''){
      setPageState({
        path: e.detail.path,
        params: e.detail.params ? e.detail.params : {},
      });
    }else{
      setPageState({
        path: e.state.path,
        params: e.state.params ? e.state.params : {},
      });
    }
  };
  window.addEventListener('customPopState',listnerHistory);  
  window.addEventListener('popstate',listnerHistory);
  useEffect(() => {
    return () => {
      window.removeEventListener('customPopState',listnerHistory,true);
      window.removeEventListener('popstate',listnerHistory,true);
      window.removeEventListener('customPopState',listnerHistory,false);
      window.removeEventListener('popstate',listnerHistory,false);
    };
  })
  if (!props.config) {
    console.warn('没有导入config文件');
    return(<></>);
  }
  const list = props.config.map((el) =>
    <HistoryRouterItem el={el} key={el.path} pageState={pageState} />
  );
  return (
    <Suspense fallback={< Loading />}>
      {list}
    </Suspense>
  )
}

function HistoryRouterItem(props) {
  const pageName = props.pageState.path;
  // console.log(props , pageName === props.el.path) 
  if (pageName && pageName === props.el.path) {
    let params = props.pageState.params;
    return (
      <>
        <props.el.component params={params} />
      </>
    )
  } else {
    return (
      <></>
    )
  }
}

function navReplace(page,pageName,params){
  const _page = {
    path: page,
    params: params ? params : {},
  }
  createCustomPopStateEvent(_page);
  history.replaceState(_page,pageName,'/#/' + pageName);
}

function navPush(page,pageName,params){
  const _page = {
    path: page,
    params: params ? params : {},
  }
  createCustomPopStateEvent(_page);
  history.pushState(_page,pageName,'/#/' + pageName);
}

function navBack(){
  history.back();
}

function createCustomPopStateEvent(page){
  let ev = new CustomEvent('customPopState',{detail: page});
  window.dispatchEvent(ev);
}


export { HashRouter, HistoryRouter, navReplace, navPush, navBack };
 